GO
if exists(	select * 
						from master.dbo.sysdatabases 
						where [name] = '$(dbname)')
begin
	declare @AllowToDropDBfromScratch bit
	declare @dbname sysname
	declare @ParmDefinition nvarchar(500)
	declare @SqlCommand nvarchar(500)

	set @dbname = '$(dbname)'		
		print '--Create. Kill all user processes with DB'
	
		use [master]
		--kill user process
		set NOCOUNT ON
		--declares our variables
		declare @KILL_ID int
		declare @QUERY varchar(320)

		declare GETEXCLUSIVE_CURSOR cursor for

		--get all SPIDs from SYSOBJECTS table which match our database
		select A.SPID
		from master.[dbo].[SYSPROCESSES] A
		join master.[dbo].[SYSDATABASES] B ON A.DBID=B.DBID
		where B.[NAME]=@dbname
			and A.[lastwaittype]<>N'CHECKPOINT_QUEUE' --was added to solve SQL Server 2008 problem with killing CHECKPOINT_QUEUE process

		open GETEXCLUSIVE_CURSOR
		fetch next from GETEXCLUSIVE_CURSOR into @KILL_ID

		while(@@fetch_status =0)
		begin

		--form drop trigger query
		set @QUERY = 'KILL '+ convert(varchar,@KILL_ID)

		exec (@QUERY)
		fetch next from GETEXCLUSIVE_CURSOR into @KILL_ID
		end

		close GETEXCLUSIVE_CURSOR
		deallocate GETEXCLUSIVE_CURSOR

		print '--Create. Create new DataBase'
		if exists (	select [name] 
								from master.dbo.sysdatabases 
								where [name] = @dbname ) 
				exec('drop database '+@dbname )

		exec('create database '+ @dbname )
end
else
begin
	set @dbname = '$(dbname)'
	print '--Create. Create new DataBase'
	exec('CREATE DATABASE '+@dbname )

end
	
